const {connectUrl, client} = require('./mqtt');

let targetTrainingBoatCode = '01'

const subscribeTopics = [
    `pc/down/dir-flow/#`,
    `pc/down/statistics/water/#`,
    `pc/down/statistics/wind/#`,
]

client.on('connect', () => {
    console.log(`mqtt客户端建立成功，服务端地址【${connectUrl}】`)
    client.subscribe(subscribeTopics, {qos: 1}, err => {
        if (!err) {
            console.log("mqtt客户端订阅成功", subscribeTopics)
        }
    })
})


client.on('message', (topic, message) => {
    const msg = message.toString();
    if (msg) {
        const messageJson = JSON.parse(msg);
        const {trainingBoatCode} = messageJson
        if (targetTrainingBoatCode !== trainingBoatCode) {
            return
        }
        // console.log("↓", topic, "\n", JSON.stringify(messageJson, null, 4))
        if (topic.startsWith(`pc/down/statistics/wind/`)) {
            const {averageDirection} = messageJson
            console.log("windDirection", averageDirection)
        } else if (topic.startsWith(`pc/down/statistics/water/`)) {
            const {averageComeDirection, averageGoDirection} = messageJson
            console.log("waterDirection", averageComeDirection, averageGoDirection)
        } else if (topic.startsWith(`pc/down/dir-flow/`)) {
            const {w, cf, gf} = messageJson
            console.log("dirFlow", w, cf, gf)
        }
    } else {
        console.error("消息为空")
    }
})
